export default {
  namespaced: true,
  state() {
    return {
      discussionList: [], // 讨论列表
      discussionDetail: {}, // 发布讨论信息
      currentDiscussionDetail: {}, // 详情页讨论信息
    };
  },
  mutations: {
    // 获取讨论区列表
    setDiscussionList(state, value) {
      state.discussionList = [...state.discussionList, ...value];
    },
    // 设置发布讨论图片id
    setDiscussionFile(state, value) {
      state.discussionDetail.picList = [];
      value.forEach((item) => {
        console.log(item);
        state.discussionDetail.picList.push(item.fileID);
      });
    },
    // 设置发布讨论信息内容
    setDiscussionDetail(state, value) {
      state.discussionDetail = value;
    },
    // 设置详情页讨论信息
    setCurrentDiscussionDetail(state, value) {
      state.currentDiscussionDetail = value;
    },
    // 清空遗留讨论数据
    clearCurrentDiscussion(state) {
      state.currentDiscussionDetail = {};
    },
    // 讨论点赞,需要将列表里的具体一条讨论修改
    addCurrentDiscussionLike(state, id) {
      const current = state.discussionList.find((item) => item._id === id);
      current.liked++;
    },
    // 添加评论
    addCurrentDiscussionComment(state, comment) {
      state.currentDiscussionDetail.commentCount++;
      state.currentDiscussionDetail.commentList.push(comment);
    },

    // 点赞评论
    likedDiscussionComment(state, id) {
      const commetList = state.currentDiscussionDetail.commentList;
      commetList.forEach((item) => {
        if (item.id === id) {
          item.liked++;
        }
      });
    },
    // 指定规则排序评论
    sortComment(state, index) {
      const commentList = state.currentDiscussionDetail.commentList;
      if (index === 0) {
        // 热度排序
        commentList.sort((a, b) => b.liked - a.liked);
      } else if (index === 1) {
        // 正序排序
        commentList.sort((a, b) => b.time.getTime() - a.time.getTime());
      } else {
        // 倒序排序
        commentList.sort((a, b) => a.time.getTime() - b.time.getTime());
      }
    },
    sortDiscussion(state, index) {
      const discussionList = state.discussionList;
      if (index === 0) {
        // 热度排序
        discussionList.sort((a, b) => b.liked - a.liked);
      } else if (index === 1) {
        // 正序排序
        discussionList.sort(
          (a, b) => b.createTime.getTime() - a.createTime.getTime()
        );
      } else {
        // 倒序排序
        discussionList.sort(
          (a, b) => a.createTime.getTime() - b.createTime.getTime()
        );
      }
    },

    // 清空讨论列表
    clearDiscussionList(state) {
      state.discussionList = [];
    },
    // 转换image -> url链接：已无必要
    // setCurrentDiscussionImage(state, value){
    //   const newList = [];
    //   value.forEach(item => {
    //     newList.push(item.tempFileURL);
    //   });
    //   state.currentDiscussionDetail.picList = newList;
    // }
  },
  actions: {
    // 获取讨论区列表
    getDiscussionList({ commit }, payload) {
      const db = wx.cloud.database(),
        { page, limitCount } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("discussion")
            .orderBy("createTime", "desc")
            .skip(page * limitCount)
            .limit(limitCount)
            .get();
          console.log(res.data);
          commit("setDiscussionList", res.data);
          //commit("sortDiscussion", 1);
          resolve("成功获取到讨论列表数据");
        } catch (err) {
          console.log(err);
          reject(err);
        }
      });
    },

    // 上传单张讨论图片
    uploadDiscussionFile({ commit }, payload) {
      const { fileName, filePath } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await wx.cloud.uploadFile({
            cloudPath: fileName,
            filePath,
          });
          console.log("上传图片：", res);
          resolve(res);
        } catch (err) {
          reject(err);
        }
      });
    },

    // 上传多张图片（最终上传）
    uploadMultipleFile({ dispatch, commit }, fileList) {
      return new Promise(async (resolve, reject) => {
        if (!fileList.length) {
          resolve("无需要上传的图片");
        }
        const uploadFileTasks = fileList.map((file) => {
          const fileName = "discussionPic/" + file.name,
            filePath = file.url;
          return dispatch("uploadDiscussionFile", {
            fileName,
            filePath,
          });
        });
        try {
          const res = await Promise.all(uploadFileTasks);
          commit("setDiscussionFile", res);
          resolve("全部上传成功");
        } catch (err) {
          console.log("上传有错误：", err);
          reject(err);
        }
      });
    },

    // 上传讨论内容
    uploadDiscussionDetail({ state, dispatch }) {
      const db = wx.cloud.database();
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db.collection("discussion").add({
            data: state.discussionDetail,
          });
          console.log("查看讨论发布：", res);
          dispatch("publishDiscussionContent", res._id, { root: true });
          await dispatch("getUserInfo", { type: 0 }, { root: true });
          resolve(res);
        } catch (err) {
          console.log("上传讨论失败：", err);
          reject(err);
        }
      });
    },

    // 获取详情页的讨论信息
    getCurrentDicussionDetail({ commit }, id) {
      const db = wx.cloud.database();
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("discussion")
            .where({ _id: id })
            .get();
          commit("setCurrentDiscussionDetail", res.data[0]);
          commit("sortComment", 0);
          // await dispatch("getTempFileUrl");
        } catch (err) {
          console.log("获取指定详情页内容失败：", err);
          reject(err);
        }
      });
    },

    // 指定讨论点赞
    likeDicussion({ commit, dispatch }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { discussionId, authorId } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("discussion")
            .where({ _id: discussionId })
            .update({
              data: {
                liked: _.inc(1),
              },
            });
          commit("addCurrentDiscussionLike", discussionId);
          dispatch("likedUser", authorId);
          resolve(res);
        } catch (err) {
          console.log("点赞失败：", err);
          reject(err);
        }
      });
    },

    // 讨论点赞同时增加用户点赞量
    likedUser({}, userId) {
      const db = wx.cloud.database(),
        _ = db.command;

      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                liked: _.inc(1),
              },
            });
          resolve("用户获赞成功");
        } catch (err) {
          console.log("用户获赞失败：", err);
          reject(err);
        }
      });
    },

    // 讨论的评论点赞
    likeDiscussionComment({ commit, state }, id) {
      const db = wx.cloud.database(),
        _ = db.command,
        discussionId = state.currentDiscussionDetail._id;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("discussion")
            .where({ _id: discussionId })
            .update({
              data: {
                [`commentList.${id - 1}.liked`]: _.inc(1),
              },
            });
          commit("likedDiscussionComment", id);
          console.log("点赞成功：", res);
          resolve(res);
        } catch (err) {
          console.log("点赞失败：", err);
          reject(err);
        }
      });
    },

    // 删除一个讨论
    deleteUserDiscussion({ commit, state, dispatch }, discussionItem) {
      const db = wx.cloud.database(),
        picList = discussionItem.picList,
        discussionId = discussionItem._id;
      return new Promise(async (resolve, reject) => {
        try {
          if (picList.length) {
            await dispatch("deleteDiscussionPicList", picList);
          }
          const res = db
            .collection("discussion")
            .where({ _id: discussionId })
            .remove();
          dispatch("deleteMyDiscussion", discussionId, { root: true });
          await dispatch("getUserInfo", { type: 0 }, { root: true });
          resolve("删除成功");
        } catch (err) {
          console.log("删除失败：", err);
          reject(err);
        }
      });
    },

    deleteDiscussionPicList({}, fileList) {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await wx.cloud.deleteFile({ fileList });
          resolve("删除成功");
        } catch (err) {
          resolve("删除图片失败");
          reject(err);
        }
      });
    },

    // 获取讨论信息拿到图片url: 没必要了焯！！！以为是这个问题显示不出图片，结果不是
    // getTempFileUrl({state, commit}){
    //   return new Promise(async (resolve, reject) =>{
    //     const picList = state.currentDiscussionDetail.picList;
    //     if(!picList.length){
    //       resolve("无需转换");
    //     }
    //     try{
    //       const res = await wx.cloud.getTempFileURL({fileList:picList});
    //       commit("setCurrentDiscussionImage", res.fileList);
    //     }catch(err){
    //       console.log("转换失败：",err);
    //       reject(err);
    //     }
    //   })
    // }
  },
};
